<template>
  <div class="container">
    <h1>问卷填写</h1>
    <el-input v-model="query.id" placeholder="请输入问卷id" class="input-with-margin"></el-input>
    <el-row class="button-row mb-4">
      <el-button round @click="fetchSurvey" class="button-with-margin">填写问卷</el-button>
      <router-link to="/Inquiry">
        <el-button round class="button-with-margin">查询问卷</el-button>
      </router-link>
    </el-row>

    <div v-if="questionnaire" class="questionnaire-container">
      <div class="title">
        <h2>{{ questionnaire.title }}</h2>
      </div>
      <div class="user">
        <p>创建者ID: {{ questionnaire.userId }}</p>
      </div>
      <p>问卷描述: {{ questionnaire.description }}</p>
      <h2>问题列表</h2>
      <ul class="question-list">
        <li v-for="question in questionnaire.questions" :key="question.id" class="question-item">
          <h3>{{ question.title }}</h3>
          <p>{{ question.description }}</p>
          <template v-if="question.type === 'radio'">
            <ul>
              <li v-for="option in question.options" :key="option.id" class="option-item">
                <input :type="question.type" :name="question.id" :id="option.id" :value="option.id" v-model="selectedOptions[question.id]">
                <label :for="option.id">{{ option.text }}</label>
              </li>
            </ul>
          </template>
          <template v-else-if="question.type === 'checkbox'">
            <ul>
              <li v-for="option in question.options" :key="option.id" class="option-item">
                <input type="checkbox" :id="option.id" :value="option.id" :checked="selectedOptions[question.id] && selectedOptions[question.id].includes(option.id)" @change="updateSelectedOptions(question.id, option.id)">
                <label :for="option.id">{{ option.text }}</label>
              </li>
            </ul>
          </template>
          <textarea v-else-if="question.type === 'textarea'" v-model="textAnswers[question.id]" placeholder="请输入您的回答" class="textarea-input"></textarea>
        </li>
      </ul>
      <button @click="submitSurvey" class="submit-button">提交问卷</button>
    </div>
  </div>
</template>

<script>
import request from '../utils/request';
import axios from "axios";
import { ElMessage } from 'element-plus';
import Administator from './Administator.vue';

export default {
  data() {
    return {
      query: {
        id: ''
      },
      survey: null,
      answers: {},
      questionnaire: null,
      selectedOptions: {}, // 用于存储单选和多选问题的选项
      textAnswers: {} // 用于存储文本框问题的回答
    };
  },
  mounted() {
    this.fetchQuestionnaireData();
  },

  methods: {
    async fetchSurvey() {
      if (!this.query.id) {
        ElMessage.warning('Please enter a survey ID');
        return;
      }
      try {
        const response = await request.get("api/survey/open", {
          params: { id: this.query.id },
        });
        if (response.code === '200') {
          this.survey = response.data;
          this.questionnaire = response.data;
          this.answers = {};
        } else {
          ElMessage.error(response.msg);
        }
      } catch (error) {
        ElMessage.error('Failed to fetch survey data');
      }
    },

    async fetchQuestionnaireData() {
      //const uuu=localStorage.getItem('token');
      //console.log(uuu);
      const id =this.$route.params.id;
      console.log(id);
      if(id===null){
      id = localStorage.getItem('questionnairedID');
  }
      console.log(id);
      const config = {
        method: 'get',
        url: 'api/survey/open',
        params: {
          id: id
        }
      };
      try {
        console.log(id);
        const response = await request(config);
        if(response.code==="200"){
        this.questionnaire = response.data;
        localStorage.removeItem('questionnairedID');
        }
        else{
          console.error("Error fetching questionnaire data:", error);
        }
      } catch (error) {
        console.error("Error fetching questionnaire data:", error);
      }
    },

    updateSelectedOptions(questionId, optionId) {
      if (!this.selectedOptions[questionId]) {
        this.selectedOptions[questionId] = [];
      }
      const index = this.selectedOptions[questionId].indexOf(optionId);
      if (index > -1) {
        this.selectedOptions[questionId].splice(index, 1); // 如果存在，移除这个选项
      } else {
        this.selectedOptions[questionId].push(optionId); // 如果不存在，添加这个选项
      }
      this.selectedOptions = { ...this.selectedOptions }; // 触发视图更新
    },

    async submitSurvey() {
      // 构建提交到后端的问题信息和选项
      const questions = this.questionnaire.questions.map((question) => {
        const options = question.options.map((option) => {
          // 默认未选中状态
          let checked = 0;
          // 若当前问题被选中，更新checked状态
          if (question.type === 'radio') {
            checked = this.selectedOptions[question.id] === option.id ? 1 : 0;
          } else if (question.type === 'checkbox') {
            checked = Array.isArray(this.selectedOptions[question.id]) && this.selectedOptions[question.id].includes(option.id) ? 1 : 0;
          }
          return {
            id: option.id,
            text: option.text,
            checked: checked
          };
        });

        return {
          id: question.id,
          title: question.title,
          description: question.description,
          type: question.type,
          options: options, // 选择题的选项数组
          text: question.type === 'textarea' ? this.textAnswers[question.id] : null, // 问答题的文本答案
        };
      });

      // 构建完整的surveyData
      const surveyData = {
        id: this.questionnaire.id,
        title: this.questionnaire.title,
        status: 1, // 假设状态为1，此处需要根据实际情况调整
        userId: this.questionnaire.userId,
        description: this.questionnaire.description,
        questions: questions
      };

      try {
        const token = localStorage.getItem('token'); // 获取token
        const response = await request.post('api/survey/commit', surveyData, {
          headers: {
            'token': token // 使用获取的token
          }
        });
        console.log("提交问卷成功响应：", response.data);
        ElMessage.success('提交问卷成功');
        this.$router.push('/Inquiry');
      } catch (err) {
        console.error("提交问卷失败错误：", error);
        ElMessage.error('提交问卷失败');
      }
    }
  }
};
</script>

<style>
.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

h1 {
  text-align: center;
  margin-bottom: 20px;
}

.input-with-margin {
  margin-bottom: 20px;
}

.button-row {
  display: flex;
  justify-content: space-between;
}

.button-with-margin {
  margin-right: 10px;
}

.questionnaire-container {
  margin-top: 20px;
  padding: 20px;
  background: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.title {
  text-align: center;
  margin-bottom: 20px;
}

.user {
  text-align: center;
  margin-bottom: 10px;
}

.question-list {
  list-style-type: none;
  padding: 0;
}

.question-item {
  margin-bottom: 20px;
  padding: 15px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.option-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.option-item input {
  margin-right: 10px;
}

.textarea-input {
  width: 100%;
  padding: 10px;
  border-radius: 4px;
  border: 1px solid #ccc;
  resize: vertical;
}

.submit-button {
  display: block;
  width: 100%;
  padding: 15px;
  background-color: #409eff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.submit-button:hover {
  background-color: #66b1ff;
}
</style>
